package com.bjfu.config;

import com.bjfu.intercepters.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Autowired
    private LoginInterceptor loginInterceptor;
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //对于"/General/**"（通用接口）不进行拦截
        registry.addInterceptor(loginInterceptor).excludePathPatterns("/General/**");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173")  // 允许的前端来源
                .allowedMethods("GET", "POST", "PUT", "DELETE")  // 允许的请求方法
                .allowedHeaders("token", "Content-Type", "Authorization")  // 确保允许 token 请求头
                .allowCredentials(true)  // 允许携带凭证（cookies、authorization header等）
                .exposedHeaders("Content-Disposition")
                .maxAge(3600);  // 预检请求的有效期（单位：秒）
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射静态资源路径
        System.out.println("file://"+System.getProperty("user.dir") + uploadDir + "/");
        registry.addResourceHandler("/uploads/**")  // 对应访问 URL
                .addResourceLocations("file:" + System.getProperty("user.dir") + uploadDir + "/");  // 文件存储的本地路径
    }
}
